package com.mengyan.codesandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.BOMInputStream;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.mengyan.codesandbox.model.ExecuteCodeRequest;
import com.mengyan.codesandbox.model.ExecuteCodeResponse;
import com.mengyan.codesandbox.model.ExecuteMessage;
import com.mengyan.codesandbox.model.JudgeInfo;
import com.mengyan.codesandbox.utils.ProcessUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class JavaNativeCodeSandbox implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;

    @Value("${codesandbox.security}")
    private String securityManagerPath;

    @Value("${codesandbox.jdk}")
    private String sandboxJdkPath;
    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";
    // TODO 改为配置
    private static final List<String> blackList = Arrays.asList("Files", "exec");

    private static final WordTree wordTree;

    static {
        // 初始化
        wordTree = new WordTree();
        wordTree.addWords(blackList);
    }
    public static void main(String[] args) {
        JavaNativeCodeSandbox javaNativeCodeSandbox = new JavaNativeCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));

        String code = ResourceUtil.readUtf8Str("testCode"+"/" +"simpleComputeArgs" + "/" + "Main.java");
        // String code = ResourceUtil.readUtf8Str("testCode"+"/" +"simpleCompute" + "/" + "Main.java");

        // String code = ResourceUtil.readUtf8Str("security"+ "/" + "MySecurityManager.java");
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");

        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);

        System.out.println(executeCodeResponse);

    }
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        // todo 需要降级至jdk17以下
        // System.setSecurityManager(new DefaultSecurityManager());
        String language = executeCodeRequest.getLanguage();
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();

        //校验代码中是否包含黑名单文本
        FoundWord foundWord = wordTree.matchWord(code);
        if (foundWord != null) {
            System.out.println("包含禁止词:" + foundWord.getFoundWord());
            return null;
        }

        String userDir =  System.getProperty("user.dir");
        // todo tmpCode 修改为配置项
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 查询工作路径是否存在
        if(FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();

        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;

        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        String compileCmd = String.format("%s"+File.separator+"javac -encoding utf-8 %s",sandboxJdkPath, userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (IOException e) {
            return getErrorResponse(e);
        }

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs: inputList) {
            // 限制内存大小 TODO 获得是否为内存溢出
            // String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);

            // 执行时配置SecurityManager
            // String runCmd = String.format("%s\\javac -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s",sandboxJdkPath, userCodeParentPath, securityManagerPath, SECURITY_MANAGER_CLASS_NAME , inputArgs);
            String runCmd = String.format("%s"+File.separator+"java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s",sandboxJdkPath, userCodeParentPath, securityManagerPath, SECURITY_MANAGER_CLASS_NAME , inputArgs);
            System.out.println(runCmd);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                // todo 粗糙的超时判断
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时中断");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                // ExecuteMessage executeMessage = ProcessUtils.runInterProcessAndGetMessage(runProcess, "运行", inputArgs);
                executeMessageList.add(executeMessage);
            } catch (IOException e) {
                return getErrorResponse(e);
            }
        }

        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }

        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }

        JudgeInfo judgeInfo = new JudgeInfo();
        // 使用第三方库完成查看使用内存
        // judgeInfo.setMemory();
        // 时间取最长
        judgeInfo.setTime(maxTime);

        executeCodeResponse.setJudgeInfo(judgeInfo);
        executeCodeResponse.setOutputList(outputList);

        // 文件清理 TODO 改为异步
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del? "成功": "失败"));
        }


        return executeCodeResponse;
    }


    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}

